﻿Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Xml.Linq
Imports Exp.Model
Imports Exp.DATA_Service

Public Class User
    Inherits System.Web.UI.Page

    Const MENUNAME As String = "USER"
    Const SaveSuccess As String = "Save completed."
    Const SaveError As String = "Save error !"
    Const DeleteSuccess As String = "Delete completed."
    Const DeleteError As String = "Delete not complete"


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("en-US")
            If Session("USER") Is Nothing Then
                Response.Redirect("~/login.aspx")
            Else
                Dim objUser As REM_User = CType(Session("USER"), REM_User)

                Dim objUSV As New Exp.DATA_Service.User_Service
                If Not objUSV.isHasRight(objUser.User_ID, MENUNAME) Then
                    Session("USER") = Nothing
                    Session.Clear()
                    Response.Redirect("login.aspx")
                End If
                MultiView1.ActiveViewIndex = 0
                BindControl()
                BindGridview()
            End If
        End If


    End Sub

    Private Sub BindControl()

        Dim itemAll As New ListItem("", "")
        Dim itemActive As New ListItem("Active", "1")
        Dim itemInactive As New ListItem("Inactive", "0")

        If Me.ddlUsernameView0.Items.Count = 0 Then
            Dim objSVUser As New User_Service
            Dim objDataUser = objSVUser.GetAll.Where(Function(o) o.isActive = True).OrderBy(Function(o) o.UserName)

            ddlUsernameView0.DataTextField = "username"
            ddlUsernameView0.DataValueField = "user_id"
            ddlUsernameView0.DataSource = objDataUser
            ddlUsernameView0.DataBind()
            ddlUsernameView0.Items.Insert(0, itemAll)
        End If

        Dim objRole As New Role_Service
        Dim objDataRole = objRole.GetAll.OrderBy(Function(o) o.Role_ID)

        If Me.ddlRoleView0.Items.Count = 0 Then
            ddlRoleView0.DataTextField = "RoleName"
            ddlRoleView0.DataValueField = "Role_id"
            ddlRoleView0.DataSource = objDataRole
            ddlRoleView0.DataBind()
            ddlRoleView0.Items.Insert(0, itemAll)
        End If

        If Me.ddlRoleView1.Items.Count = 0 Then
            ddlRoleView1.DataTextField = "RoleName"
            ddlRoleView1.DataValueField = "Role_id"
            ddlRoleView1.DataSource = objDataRole
            ddlRoleView1.DataBind()

            'ddlRoleView1.Items.Insert(0, itemAll)
        End If

        If Me.ddlStatusView0.Items.Count = 0 Then
            ddlStatusView0.Items.Add(itemAll)
            ddlStatusView0.Items.Add(itemActive)
            ddlStatusView0.Items.Add(itemInactive)
        End If

        If Me.ddlStatusView1.Items.Count = 0 Then
            ddlStatusView1.Items.Add(itemAll)
            ddlStatusView1.Items.Add(itemActive)
            ddlStatusView1.Items.Add(itemInactive)
        End If

    End Sub

    Private Sub BindGridview()
        Dim objSV As New User_Service
        Dim listData = objSV.GetAll()
        grdView0.DataSource = listData
        grdView0.DataBind()

    End Sub

    Private Sub BindDataForEdit(ByVal User_ID As Integer)
        Dim objSV As New User_Service
        Dim objUser = objSV.GetByID(User_ID)
        Me.hdUser_id.Value = User_ID

        Me.txtUserNameView1.Text = objUser.UserName
        Me.txtUserNameView1.ReadOnly = True
        'Me.txtPasswordView1.Text = objUser.UserName
        Me.ddlRoleView1.SelectedValue = objUser.Role_ID.ToString
        Me.txtTitleNameView1.Text = objUser.TitleName & ""
        Me.txtFirstNameView1.Text = objUser.FirstName & ""
        Me.txtLastNameView1.Text = objUser.LastName & ""
        Me.txtMobilePhoneView1.Text = objUser.MobilePhone & ""
        Me.txtHomePhoneView1.Text = objUser.HomePhone & ""
        Me.txtEmailView1.Text = objUser.Email & ""
        Me.txtCreditCardView1.Text = objUser.CreditcardNumber & ""
        Me.txtAddressView1.Text = objUser.Address & ""

        If objUser.JoinDate & "" <> "" Then
            Dim joindate_year As Integer = objUser.JoinDate.Value.Year
            If joindate_year > 2500 Then joindate_year = joindate_year - 543
            Me.txtJoin_DTView1.Text = objUser.JoinDate.Value.ToString("dd/MM/") & joindate_year.ToString
        End If

        Me.ddlStatusView1.SelectedValue = IIf(objUser.isActive = True, "1", "0")

        If objUser.ExpireDate & "" <> "" Then
            Dim ExpireDate_year As Integer = objUser.ExpireDate.Value.Year
            If ExpireDate_year > 2500 Then ExpireDate_year = ExpireDate_year - 543
            Me.lblExpireDateView1.Text = objUser.ExpireDate.Value.ToString("dd/MM/") & ExpireDate_year.ToString
        End If

        If objUser.LastLoginDate & "" <> "" Then
            Dim LastLoginDate_year As Integer = objUser.ExpireDate.Value.Year
            If LastLoginDate_year > 2500 Then LastLoginDate_year = LastLoginDate_year - 543
            Me.lblLastLoginDateView1.Text = objUser.LastLoginDate.Value.ToString("dd/MM/") & LastLoginDate_year.ToString
        End If
    End Sub

    Private Sub BindDataForView(ByVal User_ID As Integer)
        Dim objSV As New User_Service
        Dim objUser = objSV.GetByID(User_ID)
        Me.hdUser_id.Value = User_ID


        Me.lblUserNameView2.Text = objUser.UserName
        Me.lblRoleNameView2.Text = objUser.REM_Role.RoleName
        Me.lblTitleNameView2.Text = objUser.TitleName & ""
        Me.lblFirstNameView2.Text = objUser.FirstName & ""
        Me.lblLastNameView2.Text = objUser.LastName & ""
        Me.lblMobilePhoneView2.Text = objUser.MobilePhone & ""
        Me.lblHomePhoneView2.Text = objUser.HomePhone & ""
        Me.lblEmailView2.Text = objUser.Email & ""
        Me.lblCreditCardView2.Text = objUser.CreditcardNumber & ""
        Me.lblAddressView2.Text = objUser.Address & ""


        If objUser.JoinDate & "" <> "" Then
            Dim joindate_year As Integer = objUser.JoinDate.Value.Year
            If joindate_year > 2500 Then joindate_year = joindate_year - 543
            Me.lblJoinDate2View2.Text = objUser.JoinDate.Value.ToString("dd/MM/") & joindate_year.ToString
        End If

        Me.lblStatusView2.Text = IIf(objUser.isActive = True, "Active", "Inactive")

        If objUser.ExpireDate & "" <> "" Then
            Dim ExpireDate_year As Integer = objUser.ExpireDate.Value.Year
            If ExpireDate_year > 2500 Then ExpireDate_year = ExpireDate_year - 543
            Me.lblExpireDate2View2.Text = objUser.ExpireDate.Value.ToString("dd/MM/") & ExpireDate_year.ToString
        End If

        If objUser.LastLoginDate & "" <> "" Then
            Dim LastLoginDate_year As Integer = objUser.LastLoginDate.Value.Year
            If LastLoginDate_year > 2500 Then LastLoginDate_year = LastLoginDate_year - 543
            Me.lblLoginDateView2.Text = objUser.LastLoginDate.Value.ToString("dd/MM/") & LastLoginDate_year.ToString
        End If
        Me.MultiView1.ActiveViewIndex = 2
    End Sub

    Protected Sub btnSearchView0_Click(sender As Object, e As EventArgs) Handles btnSearchView0.Click
        SearchUser()
    End Sub

    Private Sub SearchUser()
        Dim objSV As New User_Service
        Dim user_ID As Integer = 0
        Dim listData = objSV.GetAll
        If Me.ddlUsernameView0.SelectedIndex > 0 Then listData = listData.Where(Function(o) o.User_ID = CInt(Me.ddlUsernameView0.SelectedValue.Trim)).ToList
        If Me.ddlRoleView0.SelectedIndex > 0 Then listData = listData.Where(Function(o) o.Role_ID = CInt(Me.ddlRoleView0.SelectedValue.Trim)).ToList

        If Me.txtFirstNameView0.Text.Trim <> "" Then listData = listData.Where(Function(o) o.FirstName.ToUpper.Contains(Me.txtFirstNameView0.Text.ToUpper.Trim)).ToList
        If Me.txtLastNameView0.Text.Trim <> "" Then listData = listData.Where(Function(o) o.LastName.ToUpper.Contains(Me.txtLastNameView0.Text.ToUpper.Trim)).ToList

        If Me.txtMobilePhoneView0.Text.Trim <> "" Then listData = listData.Where(Function(o) o.MobilePhone.ToUpper.Contains(Me.txtMobilePhoneView0.Text.ToUpper.Trim)).ToList
        If Me.txtEmailView0.Text.Trim <> "" Then listData = listData.Where(Function(o) o.Email.ToUpper.Contains(Me.txtEmailView0.Text.ToUpper.Trim)).ToList
        If Me.txtAddressView0.Text.Trim <> "" Then listData = listData.Where(Function(o) o.Address.ToUpper.Contains(Me.txtAddressView0.Text.ToUpper.Trim)).ToList

        If Me.ddlStatusView0.SelectedIndex > 0 Then
            Dim status As Boolean = IIf(Me.ddlStatusView0.SelectedValue.Trim = "1", True, False)
            listData = listData.Where(Function(o) o.isActive = status).ToList
        End If

        grdView0.DataSource = listData
        grdView0.DataBind()
    End Sub

    Protected Sub btnSaveView1_Click(sender As Object, e As EventArgs) Handles btnSaveView1.Click


        Dim sError As String = ""
        If Me.hdUser_id.Value.Trim <> "" Then
            sError = checkBeforeSave(False)
        Else
            sError = checkBeforeSave(True)
        End If

        If sError <> "" Then
            JavaScript.AlertMessage(Me.Page, sError)
            Exit Sub
        End If

        Dim objUser As New REM_User
        objUser.UserName = Me.txtUserNameView1.Text.Trim
        objUser.Role_ID = CInt(Me.ddlRoleView1.SelectedValue.Trim)
        objUser.TitleName = Me.txtTitleNameView1.Text.Trim
        objUser.FirstName = Me.txtFirstNameView1.Text.Trim
        objUser.LastName = Me.txtLastNameView1.Text.Trim
        objUser.MobilePhone = Me.txtMobilePhoneView1.Text.Trim
        objUser.HomePhone = Me.txtHomePhoneView1.Text.Trim
        objUser.Email = Me.txtEmailView1.Text.Trim
        objUser.CreditcardNumber = Me.txtCreditCardView1.Text.Trim
        objUser.Address = Me.txtAddressView1.Text.Trim
        objUser.isActive = IIf(Me.ddlStatusView1.SelectedValue.Trim = "1", True, False)
        If CInt(Me.ddlRoleView1.SelectedValue.Trim) = 3 Then
            Dim tempdt As New DateTime(Now.Year - 1, 1, 1)
            Dim joinDate, expiredate As DateTime

            If Me.txtJoin_DTView1.Text.Trim <> "" Then
                joinDate = Date.ParseExact(Me.txtJoin_DTView1.Text.Trim, "dd/MM/yyyy", System.Globalization.DateTimeFormatInfo.InvariantInfo) 'CDate(Me.txtJoin_DTView1.Text.Trim)
                expiredate = DateAdd(DateInterval.Day, 365, joinDate)
                objUser.JoinDate = joinDate
                objUser.ExpireDate = expiredate
            End If


        End If

        Try
            If Me.hdUser_id.Value.Trim <> "" Then
                objUser.User_ID = CInt(Me.hdUser_id.Value.Trim)
                objUser.UpdateUser = CType(Session("USER"), REM_User).User_ID
                Dim objSV As New User_Service(objUser)
                objSV.Edit()

            Else
                objUser.CreateDate = Now
                objUser.CreateUser = CType(Session("USER"), REM_User).User_ID
                objUser.Password = GetDataUtil.getMD5Hash(Me.txtPasswordView1.Text.Trim)
                Dim objSV As New User_Service(objUser)
                objSV.Add()
            End If
            JavaScript.AlertMessage(Me.Page, SaveSuccess)

            Me.txtPasswordView1.Text = ""
            Me.ddlRoleView1.SelectedValue = "3"
            Me.txtTitleNameView1.Text = ""
            Me.txtFirstNameView1.Text = ""
            Me.txtLastNameView1.Text = ""
            Me.txtMobilePhoneView1.Text = ""
            Me.txtHomePhoneView1.Text = ""

            Me.txtEmailView1.Text = ""
            Me.txtCreditCardView1.Text = ""
            Me.txtAddressView1.Text = ""
            Me.txtJoin_DTView1.Text = ""
            Me.ddlStatusView1.SelectedIndex = 0
            Me.MultiView1.ActiveViewIndex = 0
            SearchUser()
        Catch ex As Exception
            JavaScript.AlertMessage(Me.Page, SaveError)
        End Try

    End Sub

    Private Function checkBeforeSave(ByVal isAddNew As Boolean) As String
        Dim objSV As New User_Service

        Dim sError As String = ""
        If Me.txtUserNameView1.Text.Trim.Length < 4 Then sError += "- User name at least 4 characters\n"


            If isAddNew = True Then 'check username & password
                Dim obj = objSV.GetAll.Where(Function(o) o.UserName = Me.txtUserNameView1.Text.Trim).ToList
            If obj.Count > 0 Then sError += "- Exists user name. Please choose another User name\n"
                If Me.txtPasswordView1.Text.Trim.Length < 6 Then sError += "- password at least 6 characters\n"

            End If

        If Me.txtFirstNameView1.Text.Trim = "" Then sError += "- First Name must not be empty\n"
        If Me.txtMobilePhoneView1.Text.Trim = "" Then sError += "- Mobile Phone must not be empty\n"
        If Me.txtEmailView1.Text.Trim = "" Then sError += "- Email must not be empty\n"

        'If Me.ddlRoleView1.SelectedValue = 3 Then
        '    Dim joindate As Date
        '    Try
        '        joindate = Date.ParseExact(Me.txtJoin_DTView1.Text.Trim, "dd/MM/yyyy", System.Globalization.DateTimeFormatInfo.InvariantInfo) ' CDate(Me.txtJoin_DTView1.Text.Trim)
        '        If DateDiff(DateInterval.Day, Now.Date, joindate) < 30 Then
        '            sError += "- Join date at least 30 Day\n"
        '        End If
        '    Catch ex As Exception
        '        sError += "- Join date invalid format\n"
        '    End Try
        'End If

        Return sError
    End Function

    Protected Sub btnBackView1_Click(sender As Object, e As EventArgs) Handles btnBackView1.Click
        MultiView1.ActiveViewIndex = 0
    End Sub

    Protected Sub ingAddView0_Click(sender As Object, e As EventArgs) Handles ingAddView0.Click

        ClearFormView1()
        MultiView1.ActiveViewIndex = 1
    End Sub

    Private Sub ClearFormView1()
        Me.hdUser_id.Value = ""
        Me.txtUserNameView1.ReadOnly = False
        Me.txtUserNameView1.Text = ""
        Me.txtPasswordView1.Text = ""
        Me.ddlRoleView1.SelectedValue = 3
        Me.txtTitleNameView1.Text = ""
        Me.txtFirstNameView1.Text = ""
        Me.txtLastNameView1.Text = ""
        Me.txtMobilePhoneView1.Text = ""
        Me.txtHomePhoneView1.Text = ""


        Me.txtEmailView1.Text = ""
        Me.txtCreditCardView1.Text = ""
        Me.txtAddressView1.Text = ""
        Me.txtJoin_DTView1.Text = ""
        Me.ddlStatusView1.SelectedIndex = 0
    End Sub

    Private Sub ClearFormView2()
        Me.hdUser_id.Value = ""
        Me.lblUserNameView2.Text = ""
        Me.lblRoleNameView2.Text = ""
        Me.lblTitleNameView2.Text = ""
        Me.lblFirstNameView2.Text = ""
        Me.lblLastNameView2.Text = ""
        Me.lblMobilePhoneView2.Text = ""
        Me.lblHomePhoneView2.Text = ""


        Me.lblEmailView2.Text = ""
        Me.lblCreditCardView2.Text = ""
        Me.lblAddressView2.Text = ""
        Me.lblJoinDate2View2.Text = ""
        Me.lblStatusView2.Text = ""

    End Sub

    Protected Sub btnBackView2_Click(sender As Object, e As EventArgs) Handles btnBackView2.Click
        MultiView1.ActiveViewIndex = 0
    End Sub

    Protected Sub grdView0_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles grdView0.RowCommand
        Dim commandArgs As String() = e.CommandArgument.ToString().Split(",")
        Dim User_ID As Integer = CInt(commandArgs(0))

        If e.CommandName.ToString.ToUpper = "EDIT" Then
            MultiView1.ActiveViewIndex = 1
            ClearFormView1()
            BindDataForEdit(User_ID)
        ElseIf e.CommandName.ToString.ToUpper = "DELETE" Then
            Dim objSVUser As New User_Service
            objSVUser.Delete(User_ID)
            JavaScript.AlertMessage(Me.Page, DeleteSuccess)
            SearchUser()
            Exit Sub
        ElseIf e.CommandName.ToString.ToUpper = "DETAIL" Then
            ClearFormView2()
            BindDataForView(User_ID)
        End If
    End Sub

    Private Sub grdView0_RowDeleting(sender As Object, e As GridViewDeleteEventArgs) Handles grdView0.RowDeleting

    End Sub

    Private Sub grdView0_RowEditing(sender As Object, e As GridViewEditEventArgs) Handles grdView0.RowEditing

    End Sub

 
End Class